#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/select.h>

#define BUFFER_SIZE 1024

int main() {
    int sock_fd, activity;
    fd_set read_fds;
    struct sockaddr_in address;
    char buffer[BUFFER_SIZE];
    
    // 1. 创建socket
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd < 0) {
        perror("Socket creation failed");
        return 1;
    }
    
    // 2. 绑定地址（示例端口9090）
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(9090);
    if (bind(sock_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("Bind failed");
        return 1;
    }
    
    // 3. 监听连接
    if (listen(sock_fd, 1) < 0) {
        perror("Listen failed");
        return 1;
    }
    
    printf("Server running, type 'exit' to quit\n");
    
    while (1) {
        // 4. 初始化fd_set
        FD_ZERO(&read_fds);
        FD_SET(sock_fd, &read_fds);
        FD_SET(STDIN_FILENO, &read_fds);  // 监听标准输入
        
        // 5. 调用select（超时时间设为NULL，阻塞等待）
        activity = select(sock_fd + 1, &read_fds, NULL, NULL, NULL);
        if (activity < 0) {
            perror("Select error");
            break;
        }
        
        // 6. 处理标准输入事件（用户输入）
        if (FD_ISSET(STDIN_FILENO, &read_fds)) {
            if (fgets(buffer, BUFFER_SIZE, stdin) != NULL) {
                buffer[strcspn(buffer, "\n")] = 0;  // 移除换行符
                if (strcmp(buffer, "exit") == 0) {
                    printf("Quitting...\n");
                    break;
                }
                printf("You entered: %s\n", buffer);
            }
        }
        
        // 7. 处理socket连接事件
        if (FD_ISSET(sock_fd, &read_fds)) {
            struct sockaddr_in client_addr;
            socklen_t client_len = sizeof(client_addr);
            int client_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &client_len);
            if (client_fd < 0) {
                perror("Accept failed");
                continue;
            }
            
            printf("Client connected, handling...\n");
            // 简化处理：读取客户端数据并关闭连接
            int bytes_read = read(client_fd, buffer, BUFFER_SIZE);
            if (bytes_read > 0) {
                buffer[bytes_read] = '\0';
                printf("Client said: %s\n", buffer);
            }
            close(client_fd);
        }
    }
    
    close(sock_fd);
    return 0;
}